package com.settlement.system.common.util.common;

import com.alibaba.fastjson2.JSON;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.google.common.collect.Iterables.getFirst;
 
/**
 * 对象验证器
 * @author author
 * 
 */
public class BeanValidator {

    static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
 
    /**
     * 验证某个bean的参数
     * 
     * @param object 被校验的参数
     * @throws ValidationException 如果参数校验不成功则抛出此异常
     */
    @SuppressWarnings("rawtypes")
	public static <T> ConstraintViolation validate(T object) {
        //执行验证
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(object);
        //如果有验证信息，则将第一个取出来包装成异常返回
        ConstraintViolation<T> constraintViolation = getFirst(constraintViolations, null);
        if(constraintViolation!=null)
        {
        	return constraintViolation;
        }
        return null;
    }

    /**
     * 清除字段首尾的空白符、单引号
     * @param t
     * @param <T>
     * @return
     */
    public static <T> T clearBeanStringBlank(T t) {
        final String singleQuotes = "'";
        BeanMap beanMap = new BeanMap(t);
        Set set = (Set) beanMap.keySet().stream()
                .filter(s -> beanMap.get(s) instanceof String && ((String) beanMap.get(s)).contains(singleQuotes))
                .collect(Collectors.toSet());
        set.forEach(key->{
            String value = (String) beanMap.get(key);
            value = StringUtils.trim(value);
            if(value.startsWith(singleQuotes)){
                value = value.substring(1);
            }
            if(value.endsWith(singleQuotes)){
                value = value.substring(0,value.length()-1);
            }
            beanMap.put(key, value);
        });
        t = (T) JSON.parseObject(JSON.toJSONString(beanMap), t.getClass());
        return t;
    }

    public static<T> void clearBeanStringBlank(List<T> list){
        for(int i=0;i<list.size();i++){
            list.set(i, (T) clearBeanStringBlank(list.get(i)));
        }
    }
}